from .forms import RegistrationForm, LoginForm
from .models import User, db
from flask import render_template, redirect, url_for, flash
from flask_login import login_user, login_required,logout_user
from .forms import BookForm
from .models import Book
from flask import request
from flask_login import current_user
from flask_login import current_user
from datetime import datetime
from .forms import BorrowBookForm
from .forms import BorrowerForm
from .models import Borrower
from sqlalchemy import or_

def init_routes(app):
    @app.route('/')
    def home():
        return render_template('base.html',title='首页')

    @app.route('/about')
    def about():
        return "这是一个图书管理系统"

    @app.route('/register', methods=['GET', 'POST'])
    def register():
        # 创建注册表单实例
        form = RegistrationForm()
        # 如果表单提交并且验证通过
        if form.validate_on_submit():
            # 创建新用户实例，并设置用户名和电子邮件
            user = User(username=form.username.data, email=form.email.data)
            # 设置用户密码（进行加密）
            user.set_password(form.password.data)
            # 添加用户到数据库会话
            db.session.add(user)
            # 提交会话，将用户保存到数据库
            db.session.commit()
            # 显示注册成功消息
            flash('恭喜你，你现在是注册用户了！')
            # 重定向到登录页面
            return redirect(url_for('login'))
        # 渲染注册模板，传递表单实例
        return render_template('register.html', title='注册', form=form)

    # 登录视图函数，处理用户登录请求
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        form = LoginForm()
        if form.validate_on_submit():
            user = User.query.filter_by(email=form.email.data).first()
            if user and user.check_password(form.password.data):
                login_user(user)  # 记录用户登录状态
                flash('您已登录！')
                return redirect(url_for('home'))
            else:
                flash('无效的用户名或密码')
        else:
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f"Error in {getattr(form, field).label.text}:{error}")
        return render_template('login.html', title='登录', form=form)

    @app.route('/logout')
    @login_required  # 用于保护视图，确保只有已登录用户才能访问。
    def logout():
        logout_user()  # 这个函数将会话中的当前用户登出
        flash('您已注销！')
        return redirect(url_for('login'))

    @app.route('/add_book', methods=['GET', 'POST'])
    def add_book():
        form = BookForm()
        if form.validate_on_submit():
            new_book = Book(title=form.title.data, author=form.author.data,
                            available=form.available.data)
            db.session.add(new_book)
            db.session.commit()
            flash('图书添加成功！')
            return redirect(url_for('books'))
        return render_template('add_book.html', form=form)

    @app.route('/delete_book/<int:book_id>', methods=['POST'])
    def delete_book(book_id):
        book = Book.query.get_or_404(book_id)
        db.session.delete(book)
        db.session.commit()
        flash('图书删除成功！')
        return redirect(url_for('books'))

    @app.route('/delete_borrower/<int:borrower_id>', methods=['POST'])
    def delete_borrower(borrower_id):
        borrower = Borrower.query.get_or_404(borrower_id)
        db.session.delete(borrower)
        db.session.commit()
        flash('借阅者信息已删除！')
        return redirect(url_for('manage_borrowers'))

    @app.route('/edit_book/<int:book_id>', methods=['GET', 'POST'])
    def edit_book(book_id):
        book = Book.query.get_or_404(book_id)
        form = BookForm(obj=book)
        if form.validate_on_submit():
            book.title = form.title.data
            book.author = form.author.data
            book.available = form.available.data
            db.session.commit()
            flash('图书信息已更新！')
            return redirect(url_for('books'))
        return render_template('edit_book.html', form=form)

    @app.route('/edit_borrower/<int:borrower_id>', methods=['GET', 'POST'])
    def edit_borrower(borrower_id):
        borrower = Borrower.query.get_or_404(borrower_id)
        form = BorrowerForm(obj=borrower)
        if form.validate_on_submit():
            borrower.name = form.name.data
            borrower.contact = form.contact.data
            borrower.books_borrowed = form.books_borrowed.data
            db.session.commit()
            flash('借阅者信息已更新！')
            return redirect(url_for('manage_borrowers'))
        return render_template('edit_borrower.html', form=form)

    @app.route('/books')
    def books():
        all_books = Book.query.all()
        return render_template('books.html', books=all_books, title='图书列表')

    @app.route('/manage_borrowing')
    @login_required
    def manage_borrowing():
        available_books = Book.query.filter_by(available=True).all()  # 获取所有可借的书籍
        borrowed_books = Book.query.filter_by(borrower_id=current_user.id).all()  #
        #获取当前用户借阅的书籍
        if available_books ==[]:
            flash('没有可借的书籍，请先添加！')
        return render_template('manage_borrowing.html',available_books=available_books, borrowed_books=borrowed_books)
    @app.route('/borrow_book/<int:book_id>', methods=['GET', 'POST'])
    @login_required
    def borrow_book(book_id):
        book = Book.query.get_or_404(book_id)
        form = BorrowBookForm()  # 包含输入借阅者标识的文本字段的表单
        if form.validate_on_submit():
            borrower =Borrower.query.filter_by(name=form.borrower_username.data).first()
            if not borrower:
                flash('没有找到指定的借阅者。')
                return redirect(url_for('manage_borrowing'))
            if not book.available:
                flash('这本书已被借出。')
                return redirect(url_for('manage_borrowing'))
            book.available = False
            book.borrower_id = borrower.id
            book.borrowed_on = datetime.utcnow()
            borrower.books_borrowed += 1  # 增加借阅者的借书计数
            db.session.add(borrower)
            db.session.commit()
            flash('你已成功借阅这本书。')
            return redirect(url_for('manage_borrowing'))
        return render_template('borrow_book.html', form=form, book=book)

    @app.route('/return_book/<int:book_id>', methods=['POST'])
    @login_required
    def return_book(book_id):
        book = Book.query.get_or_404(book_id)

        if book.available:
            flash('这本书没有被借出。')
        return redirect(url_for('manage_borrowing'))
        # 减少借阅者的借书计数
        borrower = Borrower.query.get(book.borrower_id)
        if borrower.books_borrowed > 0:
            borrower.books_borrowed -= 1  # 减少借阅计数
        else:
            flash('借阅数据异常，请检查！')
        # 更新书籍状态
        book.available = True
        book.borrower_id = None
        book.borrowed_on = None
        db.session.commit()
        flash('你已成功归还这本书。')
        return redirect(url_for('manage_borrowing'))

    @app.route('/borrowing_history')
    @login_required
    def borrowing_history():
        borrower = Borrower.query.get_or_404(current_user.id)
        borrowed_books = Book.query.filter_by(borrower_id=borrower.id).all()
        return render_template('borrowing_history.html', books=borrowed_books)

    @app.route('/manage_borrowers', methods=['GET', 'POST'])
    def manage_borrowers():
        form = BorrowerForm()
        if form.validate_on_submit():
            new_borrower = Borrower(name=form.name.data, contact=form.contact.data)
            db.session.add(new_borrower)
            db.session.commit()
            flash('借阅者已添加！')
            return redirect(url_for('manage_borrowers'))
        borrowers = Borrower.query.all()
        if borrowers ==[]:
            flash('没有借阅者信息，请先添加！')
        return render_template('manage_borrowers.html', form=form,borrowers=borrowers)

    @app.route('/search', methods=['GET', 'POST'])
    def search():
        if request.method== "POST":
            search_query = request.form['search']
            books = db.session.query(Book).join(Borrower).filter(
                or_(
                    Book.title.contains(search_query),
                    Borrower.name.contains(search_query)
                )
            ).all()
            if books==[]:
                flash('没有找到相关图书，请重新输入！')
            return render_template('books.html', books=books)
        return render_template('search.html')




